package com.gyg.threadPool.threadCase;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 不同业务使用不同的线程池案例
 */
@Slf4j
public class ThreadCase01 {
    private static final int CORE_POOL_SIZE = 5;
    private static final int MAX_POOL_SIZE = 10;
    private static final long KEEP_ALIVE_TIME = 1;
    private static final int QUEUE_CAPACITY = 100;
    private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;

    private ThreadPoolExecutor pool;

    public ThreadCase01() {
        this.pool = createThreadPoolExecutor();
    }

    public static void main(String[] args) {
        ThreadCase01 threadCase01 = new ThreadCase01();
        for (int i = 0; i < 5; i++) {
        }
    }

    /**
     * 执行导出任务
     */
    public void executeExportTask() {
        log.info("执行导出任务...");
        //采用线程池执行导出任务
        CountDownLatch latch = new CountDownLatch(1);
        //异步执行导出任务
        pool.execute(()->{
            exportFile(latch);
        });
        try {
            //阻塞，待文件导出后才提示导出完成
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("导出任务执行完毕...");
    }

    /**
     * 导出数据处理和执行文件导出
     */
    public void exportFile(CountDownLatch latch) {
        log.info("执行导出逻辑...");
        //1、导出数据校验
        List<String> dataList = new ArrayList<>();
        CountDownLatch dataLatch = new CountDownLatch(1);
        //异步执行导出数据校验
        pool.execute(()->{
            checkExportData(dataList,dataLatch);
        });
        try {
            //阻塞，等待数据校验完成
            dataLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //2、生成文件
        generateExcelFile(dataList);
        latch.countDown();
    }

    /**
     * 导出数据校验
     */
    private void checkExportData( List<String> dataList,CountDownLatch latch) {
        log.info("执行数据校验...");
        latch.countDown();
    }

    /**
     * 生成文件
     */
    private void generateExcelFile(List<String> dataList) {
        log.info("生成Excel文件...");
    }


    public static ThreadPoolExecutor createThreadPoolExecutor() {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TIME_UNIT,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY),
                new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolExecutor;
    }
}
